package com.vichat.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.vichat.common.result.DataResult;
import com.vichat.common.result.ResultBase;
import com.vichat.common.result.ResultBaseArray;

import java.util.List;
import java.util.Map;

/**
 * Created by ranjx on 2017/3/31.
 */
public class CommonUtil {

    public static <T> ResultBase<T> parseJson(String json, Class<T> klazz) {
        ResultBase<T> base = JSON.parseObject(json, new TypeReference<ResultBase<T>>() {
        });
        T object = JSON.parseObject(JSON.toJSONString(base.getObj()), klazz);
        base.setObj(object);
        return base;
    }

    public static <T> ResultBaseArray<T> parseArray(String json, Class<T> klazz) {
        ResultBaseArray<T> base = JSON.parseObject(json, new TypeReference<ResultBaseArray<T>>() {
        });
        List<T> object = JSON.parseArray(JSON.toJSONString(base.getObj()), klazz);
        base.setObj(object);
        return base;
    }

    public static <T> DataResult<T> parseDataArray(String json, Class<T> klazz) {
        DataResult<T> base = JSON.parseObject(json, new TypeReference<DataResult<T>>() {
        });
        List<T> object = JSON.parseArray(JSON.toJSONString(base.getRows()), klazz);
        base.setRows(object);
        return base;
    }

    public static String toJson(Object obj) {
        return JSON.toJSONString(obj);
    }

    public static <T> T toObject(String json, Class<T> klazz) {
        return JSON.parseObject(json, klazz);
    }

    public static Map<String, Object> toMap(Object obj) {
        return JSON.parseObject(JSON.toJSONString(obj), new TypeReference<Map<String, Object>>() {
        });
    }

}
